package com.company.ems.controller;

import com.company.ems.mapper.EmployeeMapper;
import com.company.ems.model.User;
import com.company.ems.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/DashboardServlet")
public class DashboardServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 检查登录状态
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        // 2. 查询员工总数（仪表盘统计）
        int totalEmployee = 0;
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            totalEmployee = employeeMapper.selectTotalCount();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 3. 传递数据到页面
        request.setAttribute("loginUsername", loginUser.getUsername());
        request.setAttribute("totalEmployee", totalEmployee);
        request.getRequestDispatcher("/dashboard.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}